
--[[
	**********************
	* SvFrame - thomasfn *
	**********************
	spawnitem.lua - Loads basic item spawning functionality
]]

function PLUGIN:InitSpawnitem()
	svr.AddFlag( "cangive" )
	
	self:Command( "give", self.Give, { FLAG_CANGIVE } )
	self:Command( "giveto", self.GiveTo, { FLAG_CANGIVE } )
end

table.insert( PLUGIN.Inits, PLUGIN.InitSpawnitem )

function PLUGIN:Give( ply, args )
	if (not svr.CheckArg( args, 1, "string" )) then return ply:ChatPrint( colour.White, "Syntax: /give <item>[:meta] [amount]" ) end
	local itemdata = args[1]:explode( ":" )
	local item = itemdata[1]
	local meta = tonumber( itemdata[2] ) or 0
	local itemid = tonumber( item ) or LOOKUP_BLOCK[ item ] or LOOKUP_TOOL[ item ] or LOOKUP_ITEM[ item ]
	if (not itemid) then
		ply:ChatPrint( colour.Red, "No item found by name '", colour.White, tostring( item ), colour.Red, "'!" )
		return
	end
	local inv = ply.GetInventory()
	local b, res = pcall( inv.AddItem, inv, Item(itemid, tonumber( args[2] ) or 1) )
	if (not b) then
		ply:ChatPrint( colour.Red, "Failed to spawn item! (is the ID and meta correct?)" )
	else
		ply:ChatPrint( colour.Green, "Item '", colour.White, tostring( itemid ), colour.Green, "' spawned successfully." )
	end
end

function PLUGIN:GiveTo( ply, args )
	if (not svr.CheckArg( args, 1, "string" )) then return ply:ChatPrint( colour.White, "Syntax: /giveto <target> <item>[:meta] [amount]" ) end
	if (not svr.CheckArg( args, 2, "string" )) then return ply:ChatPrint( colour.White, "Syntax: /giveto <target> <item>[:meta] [amount]" ) end
	local plist = svr.FindPlayers( args[1] )
	if (#plist == 0) then return ply:ChatPrint( colour.Red, "No players found with that name." ) end
	if (#plist > 1) then return ply:ChatPrint( colour.Red, "Multiple players found with that partial name." ) end
	local target = plist[1]
	local itemdata = args[2]:explode( ":" )
	local item = itemdata[1]
	local meta = tonumber( itemdata[2] ) or 0
	local itemid = tonumber( item ) or LOOKUP_BLOCK[ item ] or LOOKUP_TOOL[ item ] or LOOKUP_ITEM[ item ]
	if (not itemid) then
		ply:ChatPrint( colour.Red, "No item found by name '", colour.White, tostring( item ), colour.Red, "'!" )
		return
	end
	local inv = target.GetInventory()
	local amount = tonumber( args[3] ) or 1
	local b, res = pcall( inv.AddItem, inv, Item(itemid, amount)  )
	if (not b) then
		ply:ChatPrint( colour.Red, "Failed to spawn item! (is the ID and meta correct?)" )
	else
		ply:ChatPrint( colour.Green, "You sent ", colour.White, tostring( amount ), colour.Green, " of '", colour.White, args[2], colour.Green, "' to ", svr.GetPlayerColour( target ), target.Username, colour.Green, "!" )
		svr.ChatPrint( target, colour.Green, "You received ", colour.White, tostring( amount ), colour.Green, " of '", colour.White, args[2], colour.Green, "' from ", svr.GetPlayerColour( ply ), ply.Username, colour.Green, "!" )
	end
end